<template>
  <rt-view>
    <rt-form ref="insertForm" :model="insertForm" :rules="rules">
      <rt-header>
        <rt-list-header>
          <rt-header-icon slot="icon" icon="rt-base-account" />
          <rt-header-title :sub-title="subTitle" :title="mainTitle" />
          <template slot="btn">
            <rt-header-button-group>
              <!--新增直接发布-->
              <rt-button
                v-if="!addAndUpdate"
                :plain="false"
                icon-name="rt-base-save"
                @click="publisAndSave"
              >
                发布
              </rt-button>
              <!--详情页进入编辑发布-->
              <rt-button
                v-if="addAndUpdate"
                :plain="false"
                icon-name="rt-base-save"
                @click="publisAndUpdate"
              >
                发布
              </rt-button>
              <rt-button
                v-if="addAndUpdate"
                icon-name="rt-base-close"
                @click="deleteArticle"
                >删除</rt-button
              >
            </rt-header-button-group>
            <rt-button
              v-if="!addAndUpdate"
              type="primary"
              icon-name="rt-base-save"
              style="margin-left: 10px"
              @click="save"
              >保存</rt-button
            >
            <rt-button
              v-if="addAndUpdate"
              type="primary"
              icon-name="rt-base-save"
              style="margin-left: 10px"
              @click="update"
              >保存</rt-button
            >
            <rt-button
              type="back"
              icon-name="rt-base-back"
              style="margin-left: 10px"
              @click="backTo()"
              >返回</rt-button
            >
          </template>
        </rt-list-header>
      </rt-header>
      <rt-content>
        <rt-card>
          <rt-section icon="rt-base-account" title="基础信息">
            <rt-form-wrapper ref="form1">
              <rt-row :gutter="32">
                <rt-col :span="16">
                  <rt-row :gutter="32">
                    <rt-col :span="16">
                      <rt-form-item label="文章标题" required prop="name">
                        <rt-input
                          v-model="insertForm.name"
                          placeholder="最多支持30个字"
                        />
                      </rt-form-item>
                    </rt-col>
                    <rt-col :span="8">
                      <rt-form-item
                        label="文章分类"
                        required
                        prop="bbs_article_typeidname"
                      >
                        <rt-lookup
                          ref="lookupAccount"
                          :display-fields="displayFields"
                          :fetch="getArticleType"
                          v-model="account"
                          :title="title"
                          :alias="alias"
                          @confirm="confirm"
                        />
                      </rt-form-item>
                    </rt-col>
                  </rt-row>
                  <rt-row :gutter="32">
                    <rt-col :span="2">
                      <rt-form-item>
                        <div style="text-align:center">
                          <el-checkbox v-model="insertForm.is_recommend"
                            >推荐</el-checkbox
                          >
                        </div>
                      </rt-form-item>
                    </rt-col>
                  </rt-row>
                </rt-col>
                <rt-col :span="8">
                  <rt-form-item label="封面图" prop="file">
                    <el-upload
                      ref="upload"
                      :on-preview="handlePictureCardPreview"
                      :on-remove="handleRemove"
                      :on-change="changeFile"
                      :file-list="fileList"
                      :auto-upload="false"
                      :limit="1"
                      :show-file-list="true"
                      :on-exceed="exceedLimit"
                      action=""
                      list-type="picture-card"
                      multiple
                      accept="image/jpeg,image/jpg,image/png"
                    >
                      <i class="el-icon-plus" />&nbsp;
                      <div slot="tip" class="el-upload__tip">
                        只能上传jpg/png/jpeg文件，且不可超过2M，建议尺寸750*1334
                      </div>
                    </el-upload>
                    <el-dialog :visible.sync="dialogVisible">
                      <img :src="dialogImageUrl" width="100%" alt="" />
                    </el-dialog>
                  </rt-form-item>
                </rt-col>
              </rt-row>
            </rt-form-wrapper>
          </rt-section>
        </rt-card>
        <rt-card>
          <rt-section>
            <div
              style="margin-bottom: 20px;margin-top: 20px;z-index: 1000;position: relative"
            >
              <span>写文章</span>
            </div>
            <div>
              <editor :catch-data="catchData" :content="insertForm.content" />
            </div>
          </rt-section>
        </rt-card>
      </rt-content>
    </rt-form>
  </rt-view>
</template>

<script>
import editor from '@/components/wangeditor/editor.vue';
import RtRow from 'vue-xpc/src/components/row/rtRow';
import RtCol from 'vue-xpc/src/components/col/rtCol';
import RtCard from 'vue-xpc/src/components/card/rtCard';
import RtSection from 'vue-xpc/src/components/section/rtSection';
import util from '../../libs/util';
export default {
  name: 'ArticleEdit',
  components: { RtSection, RtCard, RtCol, RtRow, editor },
  data() {
    return {
      fileList: [],
      dialogImageUrl: '',
      dialogVisible: false,
      hideUploadEdit: false,
      totalCount: '',
      title: '文章分类',
      //判断添加还是更新
      addAndUpdate: false,
      isSure: false,
      id: '',
      mainTitle: '文章',
      subTitle: '', //副标题
      formData: new FormData(),
      flag: 'nochange', //编辑时文件是否删除标识
      isUpload: true,
      errorUpload: '',
      account: null,
      total: 0,
      alias: {
        id: 'bbs_article_typeid',
        name: 'name'
      },
      displayFields: [
        {
          prop: 'name',
          label: '名称'
        },
        {
          prop: 'seq',
          label: '序号'
        }
      ],
      insertFormConfirm: '',
      insertForm: {
        name: '',
        bbs_article_typeid: '',
        bbs_article_typeidname: '',
        is_recommend: false,
        content: '',
        avatar: ''
      },
      rules: {
        name: [
          {
            required: true,
            message: '请输入文章标题',
            trigger: ['blur', 'change']
          },
          {
            max: 30,
            message: '最大长度为30个字符',
            trigger: ['blur', 'change']
          }
        ],
        bbs_article_typeidname: [
          {
            required: true,
            message: '请选择文章分类',
            trigger: ['blur', 'change']
          }
        ]
      }
    };
  },
  watch: {
    account(val) {
      if (val.name) {
        this.insertForm.bbs_article_typeidname = val.name;
        this.insertForm.bbs_article_typeid = val.bbs_article_typeid;
      } else {
        this.insertForm.bbs_article_typeidname = '';
        this.insertForm.bbs_article_typeid = '';
      }
    },
    insertForm: {
      //监听表单元素变化，变了返回就要确认
      handler(val) {
        if (val) {
          this.isSure = true;
        }
      },
      deep: true
    }
  },
  created() {
    this.addAndUpdate = this.$route.query.addAndUpdate;
    this.id = this.$route.query.id;
    if (this.id != null && this.id !== '') {
      this.getArticleById(this.id);
    }
  },
  methods: {
    confirm() {
      if (!this.editForm.account.Text) {
        this.$refs.form1.validateField('account');
      }
    },
    getArticleById(id) {
      rt.get('/api/bbs/article/detail/' + id).then(res => {
        this.insertForm = res;
        this.account = {
          bbs_article_typeid: res.bbs_article_typeid,
          name: res.bbs_article_typeidname
        };
        // this.$refs.lookupAccount.refresh();
        if (res.name) {
          this.mainTitle = res.name;
        }
        this.subTitle = res.bbs_article_statusname;
        if (res.avatar) {
          this.fileList.push({
            url: util.showRemotePic(res.avatar)
          });
          this.insertForm.avatar = res.avatar;
        }
        this.insertFormConfirm = JSON.stringify(res);
      });
    },
    getArticleType(page) {
      return this.getDataList(
        page.pageIndex,
        page.pageSize,
        page.queryValue
      ).then(resp => {
        return {
          data: resp.list,
          total: resp.count
        };
      });
    },
    getDataList(pageIndex, pageSize, queryValue) {
      return new Promise(resolve => {
        const data = {
          pageIndex: pageIndex,
          pageSize: pageSize,
          queryValue: queryValue
        };
        rt.get('/api/bbs/articletype/findtypelist', { params: data })
          .then(res => {
            resolve(res);
          })
          .catch(error => {
            rt.showErrorToast(error);
          });
      });
    },
    //选择文件
    changeFile(file) {
      const maxSize = 2 * 1024 * 1024; //2M大小
      if (file.size > maxSize) {
        rt.showErrorToast('上传图片最大不能大于2M ');
        this.$refs.upload.clearFiles();
        this.isUpload = false;
        this.errorUpload = '上传图片最大不能大于2M';
        this.fileList = [];
        return false;
      } else {
        this.isUpload = true;
        this.formData.append('file', file.raw);
        return true;
      }
    },
    //移除文件
    handleRemove(file, fileList) {
      console.log(file, fileList);
      this.formData.delete('file');
      this.flag = 'flag';
      this.fileList = [];
    },
    exceedLimit(file, fileList) {
      if (fileList.length === 1) {
        rt.showErrorToast('封面已存在，请删除后再重新上传 ');
      }
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    catchData(val) {
      this.insertForm.content = val;
    },
    //新增时保存草稿
    save() {
      this.$refs.insertForm.$children[0].validate(valid => {
        if (valid) {
          let that = this;
          that.formData.append('name', that.insertForm.name);
          that.formData.append(
            'bbs_article_typeid',
            that.account.bbs_article_typeid
          );
          that.formData.append('bbs_article_typeidname', that.account.name);
          that.formData.append('is_recommend', that.insertForm.is_recommend);
          that.formData.append('content', that.insertForm.content);
          that.formData.append('status', '1');
          let config = {
            headers: {
              'Content-Type': 'multipart/form-data'
            }
          };

          rt.post('api/bbs/article/save', that.formData, config)
            .then(res => {
              rt.showSuccessToast('成功');
              this.$router.replace({
                name: 'bbsarticledetail',
                query: { addAndUpdate: false, id: res }
              });
            })
            .catch(error => {
              that.formData = new FormData();
              rt.showErrorToast(error);
            });
        } else {
          return false;
        }
      });
    },
    //编辑时保存
    update() {
      this.$refs.insertForm.$children[0].validate(valid => {
        if (valid) {
          let that = this;
          that.formData.append('name', that.insertForm.name);
          that.formData.append(
            'bbs_article_typeid',
            that.account.bbs_article_typeid
          );
          that.formData.append('bbs_article_typeidname', that.account.name);
          that.formData.append('is_recommend', that.insertForm.is_recommend);
          that.formData.append('content', that.insertForm.content);
          that.formData.append('bbs_articleid', that.id);
          that.formData.append('status', '1');
          let config = {
            headers: {
              'Content-Type': 'multipart/form-data'
            }
          };
          if (that.formData.get('file') != null) {
            this.flag = 'nochange';
          }
          rt.post(`api/bbs/article/modify/${this.flag}`, that.formData, config)
            .then(res => {
              rt.showSuccessToast('成功');
              this.flag = 'nochange';
              this.$router.replace({
                name: 'bbsarticledetail',
                query: { addAndUpdate: false, id: res }
              });
            })
            .catch(error => {
              that.formData = new FormData();
              rt.showErrorToast(error);
            });
        } else {
          return false;
        }
      });
    },
    //新增页直接发布
    publisAndSave() {
      this.$refs.insertForm.$children[0].validate(valid => {
        if (valid) {
          let that = this;
          that.formData.append('name', that.insertForm.name);
          that.formData.append(
            'bbs_article_typeid',
            that.account.bbs_article_typeid
          );
          that.formData.append('bbs_article_typeidname', that.account.name);
          that.formData.append('is_recommend', that.insertForm.is_recommend);
          that.formData.append('content', that.insertForm.content);
          that.formData.append('status', '2');
          let config = {
            headers: {
              'Content-Type': 'multipart/form-data'
            }
          };
          rt.post('api/bbs/article/save', that.formData, config)
            .then(res => {
              rt.showSuccessToast('成功');
              this.flag = 'nochange';
              this.$router.replace({
                name: 'bbsarticledetail',
                query: { addAndUpdate: false, id: res }
              });
            })
            .catch(error => {
              that.formData = new FormData();
              rt.showErrorToast(error);
            });
        } else {
          return false;
        }
      });
    },
    //详情页进入编辑发布
    publisAndUpdate() {
      this.$refs.insertForm.$children[0].validate(valid => {
        if (valid) {
          let that = this;
          that.formData.append('name', that.insertForm.name);
          that.formData.append(
            'bbs_article_typeid',
            that.account.bbs_article_typeid
          );
          that.formData.append('bbs_article_typeidname', that.account.name);
          that.formData.append('is_recommend', that.insertForm.is_recommend);
          that.formData.append('content', that.insertForm.content);
          that.formData.append('bbs_articleid', that.id);
          that.formData.append('status', '2');
          let config = {
            headers: {
              'Content-Type': 'multipart/form-data'
            }
          };
          if (that.formData.get('file') != null) {
            this.flag = 'nochange';
          }
          rt.post(`api/bbs/article/modify/${this.flag}`, that.formData, config)
            .then(res => {
              rt.showSuccessToast('成功');
              this.flag = 'nochange';
              this.$router.replace({
                name: 'bbsarticledetail',
                query: { addAndUpdate: false, id: res }
              });
            })
            .catch(error => {
              rt.showErrorToast(error);
            });
        } else {
          return false;
        }
      });
    },
    //删除
    deleteArticle() {
      this.$confirm('确定要删除该文章?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          const idList = [];
          idList.push(this.id);
          rt.post('/api/bbs/article/delete', idList)
            .then(res => {
              if (res.ErrorCode === 0) {
                rt.showSuccessToast('成功');
                this.$router.push({ path: '/article/list' });
              }
            })
            .catch(error => {
              rt.showErrorToast(error);
            });
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
    },
    //返回
    backTo() {
      if (this.isSure) {
        this.backArticleList();
      } else {
        this.backToLastPage();
      }
    },
    //页面改变带确认
    backArticleList() {
      this.$confirm(
        '文章未保存，返回后编辑内容将不保存，是否确定返回',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          if (this.id !== '' && this.id != null) {
            this.$router.replace({
              name: 'bbsarticledetail',
              query: { addAndUpdate: false, id: this.id }
            });
          } else {
            this.$router.push({ path: '/article/list' });
          }
        })
        .catch(() => {});
    },
    //页面未改变直接返回上一页面
    backToLastPage() {
      if (this.id !== '' && this.id != null) {
        this.$router.replace({
          name: 'bbsarticledetail',
          query: { addAndUpdate: false, id: this.id }
        });
      } else {
        this.$router.push({ path: '/article/list' });
      }
    }
  }
};
</script>

<style scoped></style>
